import { getLocalStorage } from '@/utils'
import { busEnum } from '@/utils/enum'
import eventEmitter from '@/utils/eventEmitter'
import { message } from 'antd'
import { AxiosResponse, history, RequestConfig } from 'umi'

// 请求头枚举
const REQUEST_CONTENT_TYPE_ENUM: any = {
  default: 'application/x-www-form-urlencoded',
  json: 'application/json',
  'form-data': 'multipart/form-data',
}
let flag = { loading: false }

export const myRequest: RequestConfig = {
  timeout: 1000 * 10, // 延时
  requestInterceptors: [
    // request 请求拦截器
    [
      (url, options) => {
        const { dataType = 'json', headers, loading } = options
        flag.loading = loading
        if (flag.loading) {
          eventEmitter.emit(busEnum.LOADING_FLAG, true)
        }
        // 配置clientId
        const userModel = getLocalStorage('userModel')
        if (userModel && userModel.clientId) headers['clientId'] = userModel.clientId

        // 默认Content-Type
        headers['Content-Type'] = REQUEST_CONTENT_TYPE_ENUM[dataType]
        // 默认请求拼接
        // const urlPrefix = '/api'
        // const fullUrl = urlPrefix + url

        return { url, options }
      },
      // 错误处理
      (error: any) => {
        return Promise.reject(error)
      },
    ],
  ],
  responseInterceptors: [
    // response 响应拦截器
    [
      (response: AxiosResponse<any, any>) => {
        const { data = {}, config, request } = response

        // code统一处理
        switch (data.code) {
          // 未登录以及token过期或无效
          case 102008:
            localStorage.clear()
            history.push('/login')
            break
        }

        // success处理
        if (data.code === 200) {
          // 登陆单独处理
          if (request.responseURL.includes('/user_info/login')) return response
          console.log(response, '???')
          flag.loading && eventEmitter.emit(busEnum.LOADING_FLAG, false)
          return response.data
        } else {
          if (data.msg === '停止录像失败,错误码:调用次序错误') {
            return data
          }
          message.error(data.msg)
        }
        eventEmitter.emit(busEnum.LOADING_FLAG, false)
        return Promise.reject(
          `url:${config.url}返回值异常,code:${data.code},message:${data.msg},data:${JSON.stringify(data.data)}`
        )
      },
      // 错误处理
      (error: any) => {
        message.error(error?.config?.url + '接口异常')
        eventEmitter.emit(busEnum.LOADING_FLAG, false)
        return Promise.reject(error)
      },
    ],
  ],
}
